<template>
	<view class="container">
		<view class="head">
			<view class="left-icon"><uni-icons class="icon" color="#a1a0a0" type="left" size="22"></uni-icons></view>
			<view class="content">
				<view class="title">{{user.userName}}</view>
				<view class="type">{{user.company}}</view>
			</view>
			<view class="btn" @click="enterComp">进入展厅</view>
		</view>

		<scroll-view scroll-y class="scroll-view">
			 <view class="data">
				  <view class="item" v-for="item in list" :key="item.id">
            <view style="width: 100%;color: #c3c9d3;text-align: center;">{{item.createAt}}</view>
					  <view class="user" v-if="item.left">
						  <image class="avatrar" :src="item.portrait" />
						  <view class="text">{{item.content}}</view>
					  </view>
					  <view class="user right" style="width: 100%;" v-else>
              <view class="text">{{item.content}}</view>
              <image class="avatrar" :src="item.portrait" />
					  </view>
				  </view>
			 </view>
		</scroll-view>

		<view class="fixed-btn">
			 <input placeholder="请输入" v-model="content" @keyup.enter="submit"/>
			 <view class="btn" @click="submit">发送</view>
		</view>
	</view>
</template>

<script>
import chatDetailApi from '@/api/chatDetail.js';
import commonMethod from '@/utils/commonMethod.js';

	export default {
		data() {
			return {
        list: [],
        user: {},
        content: '',
        groupId: '',
        oldlength: 0,
        demandId: '',//需求id
        productId: '',//产品id
        sixin: '',//私信
        showroom: '',//展厅
        demandInfo: {
          title: '',
          content: '',
          createAt: '',
        },//需求详情
        productInfo: {banList:[]},//产品详情
        showSendDemand: false,
        showSendProduct: false
			}
		},

    onLoad(options) {
      this.demandId = options.demandId;
      this.productId =  options.productId;
      this.sixin =  options.sixin;
      this.showroom = options.showroom;

      //如果是从需求跳转过来的
      if (this.demandId) {
        this.showSendDemand = true
        chatDetailApi.getDemandDetail(this.demandId).then(res=>{
          this.demandInfo = res.data.nocDemand;
          this.demandInfo.createAt = this.demandInfo.createAt.replaceAll('-', '.').slice(0, 10)
        })
      }

      //如果是从产品跳转过来的
      if (this.productId) {
        this.showSendProduct = true
        //获取根据id获取产品
        chatDetailApi.getProductById(this.productId).then(res => {
          this.productInfo = res.data.nocProduct
          //处理价格为0的产品-改为询价
          if (this.productInfo.price == 0) {
            this.productInfo.price = "询价"
          } else {
            this.productInfo.price = "￥" + this.productInfo.price
          }
          //
          let imgString = this.productInfo.banarImg
          this.productInfo.banList = imgString.split(',')
        })
      }

      //获取聊天记录
      chatDetailApi.getChatDetail({
        id: options.id,
        toUserId:  options.toUserId
      }).then(res => {
        this.groupId = res.data.nocMsgContentVo.groupId;
        this.list = res.data.nocMsgContentVo.list;
        var reg1 =new RegExp("\\*\\[\\*","g");
        var reg2 =new RegExp("\\*\\]\\*","g");
        //处理聊天记录
        this.list.forEach((value, index, array) => {
          array[index].content = value.content.replace(reg1, '')
          array[index].content = value.content.replace(reg2, '')
        })
        this.user = res.data.nocMsgContentVo.user;
        //let ele = document.getElementById('dialog');
        //ele.scrollTop = ele.scrollHeight;
      });
    },

    mounted: function () {
      //setInterval(this.query, 10000);
    },

    updated() {
      // 聊天定位到底部
      /*if (this.list.length != this.oldlength) {
        let ele = document.getElementById('dialog');
        ele.scrollTop = ele.scrollHeight;
      }
      this.oldlength = this.list.length*/
    },

    methods: {

      //获取聊天记录
      query() {
        chatDetailApi.getChatDetail({
          id: this.groupId
        }).then(res => {
          this.list = res.data.nocMsgContentVo.list;
          var reg1 =new RegExp("\\*\\[\\*","g");
          var reg2 =new RegExp("\\*\\]\\*","g");
          //处理聊天记录
          this.list.forEach((value, index, array) => {
            array[index].content = value.content.replace(reg1, '')
            array[index].content = value.content.replace(reg2, '')
          })
          this.user = res.data.nocMsgContentVo.user;
        })
      },

      //返回
      back() {
        window.location.href = baseURL + "h5/messgae.html"
      },

      mounted: function () {
        setInterval(this.query, 10000);
      },

      updated() {
        // 聊天定位到底部
        if (this.list.length != this.oldlength) {
          let ele = document.getElementById('dialog');
          ele.scrollTop = ele.scrollHeight;
        }
        this.oldlength = this.list.length
      },

      submit: async function () {
        /*const result = await judgeNocuserUserInfo()
        if (!result) {
          return
        }*/
        if (!this.content) {
          return;
        }
        //重复信息不能连续发送超过5次
        let contents = uni.getStorageSync('contentM');
        if (contents) {
          contents = JSON.parse(contents);
          if (contents.content == this.content) {
            if (contents.num < 5) {
              let contentM = {
                'content': this.content,
                'num': contents.num + 1
              };
              uni.setStorageSync('contentM', JSON.stringify(contentM));
            } else {
              layer.open({
                content: '不能频繁发送重复信息'
                , btn: '我知道了'
              });
              return;
            }
          } else {
            let contentM = {
              'content': this.content,
              'num': 1
            };
            uni.setStorageSync('contentM', JSON.stringify(contentM));
          }
        } else {
          let contentM = {
            'content': this.content,
            'num': 1
          };
          uni.setStorageSync('contentM', JSON.stringify(contentM));
        }

        //发送消息
        chatDetailApi.sendMsg(
            {
              groupId: this.groupId,
              content: this.content,
              demandId: this.demandId,
              productId: this.productId,
              siXin: this.sixin,
              showroom: this.showroom
            }
        ).then(res=>{
          this.content = ''
          this.query();
          commonMethod.getMsgGrop(this.groupId).then(res => {
            let gropList = [...res.data.msgGrop]
            gropList.forEach((value, index, array) => {
              if (null != this.demandId) {
                commonMethod.recordBrowse(5, value.fromUserId, this.demandId, 2)
              }
              commonMethod.recordBrowse(5, value.fromUserId, value.toUserId, 3)
            })
          });
          this.templateMsgSend({msgId:res.data.msgId})
        })
      },

      templateMsgSend({msgId}) {
        chatDetailApi.sendTemplateMsg(msgId);
      },

      /**
       * 发送需求详情
       */
      async sendDemandOrProductDetail(divName) {
        const result = await judgeNocuserUserInfo()
        if (!result) {
          return
        }
        let sendDiv = document.getElementById(divName)
        sendDiv.style.display = 'block'
        sendDiv.setAttribute('id', '');
        let tmpNode = document.createElement('div')
        tmpNode.appendChild(sendDiv)
        let divHtml = tmpNode.innerHTML
        tmpNode = node = null; // 解除引用，以便于垃圾回收
        //发送消息
        chatDetailApi.sendMsg(
            {
              groupId: this.groupId,
              content: divHtml,
              demandId: this.demandId,
              productId: this.productId,
              siXin: this.sixin,
              showroom: this.showroom
            }
        ).then(res=>{
          this.content = ''
          this.query();
          commonMethod.getMsgGrop(this.groupId).then(res => {
            let gropList = [...res.data.msgGrop]
            gropList.forEach((value, index, array) => {
              if (null != this.demandId) {
                commonMethod.recordBrowse(5, value.fromUserId, this.demandId, 2)
              }
              commonMethod.recordBrowse(5, value.fromUserId, value.toUserId, 3)
            })
          })
          switch (divName) {
            case 'sendDemandHTML':
              this.showSendDemand = false;
              break;
            case 'sendProductHTML':
              this.showSendProduct = false;
              break;
          }
        })
      },

      /**
       * 进入个人展厅
       */
      enterComp() {
        uni.redirectTo({
          url: '/pages/product/showroom/showroom?userId=' + this.user.id
        })
      },

      /**
       * 进入个人主页
       */
      enterPersonal() {
        window.location.href = '/h5/anchorHomepage.html?userId=' + this.user.id;
      },

      /**
       * 点击头像进入展厅或者主页
       */
      enterMy(item) {
        axios({
          method: 'post',
          url: '/h5/nocuser/info/'+item.creator,
          data: {}
        }).then(res => {
          if(res.data.code == 0){
            enterPersonalByType(res.data.nocUser);
          }
        })
      }
    }


	}
</script>

<style lang="scss">
	.head{
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.left-icon{
			
			padding: $interval $interval-min;
		}
		.content{
			text-align: center;
			.title{
				font-size: $font-size-max;
				font-weight: bold;
			}
			.type{
				margin-top:5rpx;
				font-size: $font-size-min;
			}
		}
		.btn{
			padding: 10rpx $interval;
			background-color: $color-primary;
			font-size: $font-size-min;
			color: #fff;
			border-radius: 10rpx;
			margin-right: $interval;
		}
	}
	.scroll-view{
		height: calc(100% - 215rpx);
		.data{
		
			.item{
				padding:$interval-min  $interval;
				/*display: flex;*/
				.user{
					display: flex;
					
					.avatrar{
						flex-shrink: 0;
						width: 70rpx;
						height: 70rpx;
						border-radius: 50%;
						margin-right: 16rpx;
					}
					.text{
						/*width: 70%;*/
						background: $color-primary;
						color: #fff;
						border-radius: 10rpx;
						padding:20rpx;
            max-width: 80%;
					}
				}
				.right{
					display: flex;
					justify-content: flex-end;
					.avatrar{
						margin-left: 16rpx;
						margin-right: 0px;
					}
				}
			}
		}
	}
	.fixed-btn{
		height: 100rpx;
		background-color: #fff;
		z-index: 3;
		width: 100%;
		position: fixed;
		left:0px;
		bottom:0px;
		display: flex;
		align-items: center;
		input{
			height: 60rpx;
			border-radius: 30rpx;
			flex: 1;
			padding-left: $interval;
			background-color: $bg-color;
			margin-left: $interval;
			font-size: 24rpx;
		}
		.btn{
			line-height: 60rpx;
			border-radius: 30rpx;
			padding: 0px $interval;
			color: #fff;
			margin:0px $interval;
			background-color: $color-primary;
		}
	}

</style>
